﻿//-----------------------------------------------------------------------
// <copyright file="AttributeNodeUtility.cs">
//     Copyright (c) Nicole Calinoiu. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;

using Microsoft.FxCop.Sdk;

namespace Bordecal.FxCop.Sdk
{
	/// <summary>
	/// Extension methods for the <see cref="AttributeNode"/> type.
	/// </summary>
	public static class AttributeNodeUtility
	{
		/// <summary>
		/// Gets the value of a positional attribute argument.
		/// </summary>
		/// <typeparam name="T">The type of the value.</typeparam>
		/// <param name="attribute">The attribute instance from which to retrieve the value.</param>
		/// <param name="position">The position of the target argument.</param>
		/// <returns>The typed value of the attribute argument.</returns>
		public static T GetPositionalArgumentValue<T>(this AttributeNode attribute, int position)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}

			return (T)((Literal)attribute.GetPositionalArgument(position)).Value;
		}

		/// <summary>
		/// Gets the value of a named attribute argument.
		/// </summary>
		/// <typeparam name="T">The type of the value.</typeparam>
		/// <param name="attribute">The attribute instance from which to retrieve the value.</param>
		/// <param name="name">The name of the target argument.</param>
		/// <returns>The typed value of the attribute argument.</returns>
		public static T GetNamedArgumentValue<T>(this AttributeNode attribute, string name)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}

			if (string.IsNullOrEmpty(name))
			{
				throw new ArgumentNullException("name");
			}

			var argument = attribute.GetNamedArgument(Identifier.For(name)) as Literal;
			return (argument == null) ? default(T) : (T)argument.Value;
		}
	}
}